package com.example.gss.ServiceImpl;

import com.example.gss.entity.ScholarshipApplication;
import com.example.gss.entity.Student;
import com.example.gss.enums.GradeType;
import com.example.gss.mapper.ScholarshipApplicationMapper;
import com.example.gss.Service.ScholarshipApplicationService;
import com.example.gss.Service.ScoreCalculationService;
import com.example.gss.Service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ScholarshipApplicationServiceImpl implements ScholarshipApplicationService {

    @Autowired
    private ScholarshipApplicationMapper scholarshipApplicationMapper;

    @Autowired
    private ScoreCalculationService scoreCalculationService;

    @Autowired
    private StudentService studentService;

    @Override
    @Transactional
    public ScholarshipApplication createApplication(ScholarshipApplication application) {
        // 计算总分
        application.setTotalScore(calculateTotalScore(application));
        scholarshipApplicationMapper.insert(application);
        return application;
    }

    @Override
    public List<ScholarshipApplication> getAllApplications() {
        return scholarshipApplicationMapper.selectAll();
    }

    @Override
    public Optional<ScholarshipApplication> getApplicationById(String applicationId) {
        return Optional.ofNullable(scholarshipApplicationMapper.selectById(applicationId));
    }

    @Override
    @Transactional
    public ScholarshipApplication updateApplication(ScholarshipApplication application) {
        // 重新计算总分
        application.setTotalScore(calculateTotalScore(application));
        scholarshipApplicationMapper.update(application);
        return application;
    }

    @Override
    @Transactional
    public void deleteApplication(String applicationId) {
        scholarshipApplicationMapper.delete(applicationId);
    }

    @Override
    public List<ScholarshipApplication> findApplicationsByStudentId(String studentId) {
        return scholarshipApplicationMapper.selectByStudentId(studentId);
    }

    @Override
    public List<ScholarshipApplication> findApplicationsByScholarshipId(String scholarshipId) {
        return scholarshipApplicationMapper.selectByScholarshipId(scholarshipId);
    }

    @Override
    public List<ScholarshipApplication> findApplicationsByStatus(String status) {
        return scholarshipApplicationMapper.selectByStatus(status);
    }

    @Override
    @Transactional
    public ScholarshipApplication recalculateTotalScore(String applicationId) {
        Optional<ScholarshipApplication> applicationOptional = getApplicationById(applicationId);
        if (applicationOptional.isPresent()) {
            ScholarshipApplication application = applicationOptional.get();
            application.setTotalScore(calculateTotalScore(application));
            scholarshipApplicationMapper.update(application);
            return application;
        }
        return null;
    }

    @Override
    public boolean hasExistingApplication(String studentId, String scholarshipId) {
        ScholarshipApplication existing = scholarshipApplicationMapper.selectByStudentIdAndScholarshipId(studentId, scholarshipId);
        return existing != null;
    }

    @Override
    public Optional<ScholarshipApplication> getExistingApplication(String studentId, String scholarshipId) {
        ScholarshipApplication existing = scholarshipApplicationMapper.selectByStudentIdAndScholarshipId(studentId, scholarshipId);
        return Optional.ofNullable(existing);
    }

    @Override
    @Transactional
    public ScholarshipApplication createOrUpdateApplication(ScholarshipApplication application) {
        // 检查是否已存在申请
        Optional<ScholarshipApplication> existingOptional = getExistingApplication(application.getStudentId(), application.getScholarshipId());
        
        if (existingOptional.isPresent()) {
            // 如果已存在，则更新现有申请
            ScholarshipApplication existing = existingOptional.get();
            application.setApplicationId(existing.getApplicationId());
            application.setApplyDate(new Date()); // 更新申请日期
            application.setStatus("申请中"); // 重置状态为待审核
            application.setTotalScore(calculateTotalScore(application));
            
            // 确保其他字段不为空
            if (application.getIdeologyScore() == null) {
                application.setIdeologyScore(BigDecimal.ZERO);
            }
            if (application.getAcademicScore() == null) {
                application.setAcademicScore(BigDecimal.ZERO);
            }
            if (application.getResearchScore() == null) {
                application.setResearchScore(BigDecimal.ZERO);
            }
            if (application.getServiceScore() == null) {
                application.setServiceScore(BigDecimal.ZERO);
            }
            
            scholarshipApplicationMapper.update(application);
            return application;
        } else {
            // 如果不存在，则创建新申请
            // 生成申请ID
            application.setApplicationId(java.util.UUID.randomUUID().toString());
            // 设置申请日期
            application.setApplyDate(new Date());
            // 设置默认状态为申请中
            application.setStatus("申请中");
            // 设置默认分数为0
            application.setTotalScore(calculateTotalScore(application));
            if (application.getIdeologyScore() == null) {
                application.setIdeologyScore(BigDecimal.ZERO);
            }
            if (application.getAcademicScore() == null) {
                application.setAcademicScore(BigDecimal.ZERO);
            }
            if (application.getResearchScore() == null) {
                application.setResearchScore(BigDecimal.ZERO);
            }
            if (application.getServiceScore() == null) {
                application.setServiceScore(BigDecimal.ZERO);
            }
            
            scholarshipApplicationMapper.insert(application);
            return application;
        }
    }

    /**
     * 根据学生年级计算总分
     */
    private BigDecimal calculateTotalScore(ScholarshipApplication application) {
        // 获取学生信息
        Optional<Student> studentOptional = studentService.getStudentById(application.getStudentId());
        if (studentOptional.isPresent()) {
            Student student = studentOptional.get();
            GradeType gradeType = GradeType.fromGradeName(student.getGrade());
            return scoreCalculationService.calculateTotalScore(application, gradeType);
        }
        return BigDecimal.ZERO;
    }
}